import axios from 'axios'
import {useRouter} from "vue-router";
import { ElNotification } from 'element-plus'

const router = useRouter()
const request = axios.create({
    timeout: 10000
})

// request 拦截器
let user = null
request.interceptors.request.use(config => {
    config.headers['Content-Type'] = 'application/json;charset=utf-8';
    user = localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : null;
    // if (user) {
    //     config.headers['token'] = user.token;  // 设置请求头
    // }
    return config
}, error => {
    return Promise.reject(error)
});

// response 拦截器
// 可以在接口响应后统一处理结果
request.interceptors.response.use(
    response => {
        let res = response.data;
        // 如果是返回的文件
        if (response.config.responseType === 'blob') {
            return res
        }
        // 兼容服务端返回的字符串数据
        if (typeof res === 'string') {
            res = res ? JSON.parse(res) : res
        }
        if (res.code === 0) {
            console.log(res)
            ElNotification({
                title: 'Error',
                message: res.msg,
                type: 'error',
            })
            // Router.push("/login")
        }
        return res;
    },
    error => {
        console.log('err' + error) // for debug
        return Promise.reject(error)
    }
)

export default request